<?php


namespace chixian\Libraries\Exception\Handler;


use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use chixian\Libraries\Exception\BaseException;
use chixian\Libraries\HttpServer\ResponseInterface as ResponseInterfaceLib;

/**
 * 基类异常处理句柄
 * Class BaseExceptionHandler
 * @package chixian\Libraries\Exception\Handler
 */
class BaseExceptionHandler extends ExceptionHandler
{
    /** @var StdoutLoggerInterface  */
    protected $logger;

    /** @var ResponseInterfaceLib */
    protected $response;

    public function __construct(StdoutLoggerInterface $logger, ResponseInterfaceLib $response)
    {
        $this->logger = $logger;
        $this->response = $response;
    }

    /**
     * 基类异常处理
     * @param Throwable|BaseException $throwable
     * @param ResponseInterface $response
     * @return ResponseInterface
     */
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $message = sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile());
        $this->logger->error($message, ['trace' => $throwable->getTraceAsString()]);
        $this->stopPropagation();
        return $this->response->rJson($throwable->getData(), $throwable->getRecode(), $throwable->getMessage());
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof BaseException;
    }
}